package com.itheima.springsecurity;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SpringSecurityUserDetailService implements UserDetailsService {

    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

       User user =  userService.findUserByName(username);
       List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();  //存放权限

       if(user==null){
           return null;
       }else{

//           for (Role role: user.getRoles()){
//               list.add(new SimpleGrantedAuthority(role.getKeyword()));
//
//               for (Permission permission:role.getPermissions()){
//                   list.add(new SimpleGrantedAuthority(permission.getKeyword()));
//               }
//           }

           user.getRoles().stream().forEach((role)->{
               list.add(new SimpleGrantedAuthority(role.getKeyword()));

               role.getPermissions().stream().forEach((permission -> {
                   list.add(new SimpleGrantedAuthority(permission.getKeyword()));
               }));
           });


       }


        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);
    }
}
